package com.moonciki.artadmin.core.base;

import com.moonciki.artadmin.core.constant.GlobalConstant;
import com.moonciki.artadmin.core.exception.CustomException;
import com.moonciki.artadmin.core.model.FileWrapper;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;

@Slf4j
public class BaseController {

    /**
     * 返回附件格式
     */
    public void responseFile(HttpServletResponse response, FileWrapper fileWrapper) {
        byte[] fileBytes = fileWrapper.getDataBytes();
        String fileName = fileWrapper.getFileName();

        OutputStream output = null;
        try {
            response.reset();
            response.setHeader("Content-Disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));
            response.setHeader("Connection", "close");
            response.setHeader("Content-Type", "application/octet-stream");

            output = response.getOutputStream();
            output.write(fileBytes);

        } catch (IOException e) {
            log.error("Download File ERROR:", e);
        }finally {
            if(output != null){
                try {
                    output.flush();
                    output.close();
                } catch (IOException e) {
                    log.error("", e);
                }
            }
        }
    }

    /**
     * 直接返回流
     */
    public void responseBytes(HttpServletResponse response, byte[] fileBytes) {
        OutputStream output = null;
        try {
            output = response.getOutputStream();
            output.write(fileBytes);
        } catch (IOException e) {
            log.error("Download File ERROR:", e);
            responseNotfound(response);
        }finally {
            if (output != null) {
                try {
                    output.flush();
                    output.close();
                } catch (IOException e) {
                    throw CustomException.createException(e);
                }
            }
        }
    }

    /**
     * 未找到资源
     * @param response
     * @throws Exception
     */
    public void responseNotfound(HttpServletResponse response) {
        try {
            response.sendError(GlobalConstant.HttpCode.no_found);
        } catch (IOException e) {
            throw CustomException.createException(e);
        }
    }

}
